package utils

import (
	"encoding/json"
)

// ToJSON outputs the JSON representation of the HashMap.
func (m *HashMap[K, V]) ToJSON() ([]byte, error) {
	return json.Marshal(m.Map())
}

// FromJSON populates the HashMap from the input JSON representation.
func (m *HashMap[K, V]) FromJSON(data []byte) error {
	elements := make(map[K]V)
	err := json.Unmarshal(data, &elements)
	if err == nil {
		m.Clear()
		for key, value := range elements {
			m.m[key] = value
		}
	}
	return err
}

// UnmarshalJSON @implements json.Unmarshaler
func (m *HashMap[K, V]) UnmarshalJSON(bytes []byte) error {
	return m.FromJSON(bytes)
}

// MarshalJSON @implements json.Marshaler
func (m *HashMap[K, V]) MarshalJSON() ([]byte, error) {
	return m.ToJSON()
}
